<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.bootcss.com/vue/2.6.11/vue.js"></script>
    <title>$set实例方法</title>
    <script>
        window.onload = function () {
            var vm = new Vue({
                el: '#mydiv',
                data: {
                    name: 'tom',
                    user: {
                        name: 'jack',
                        age: 18
                    },
                    imgs:['photo-1.jpg','photo-2.jpg','photo-3.jpg','photo-4.jpg'],
                    imgIndex:0 //需要更换的图片索引
                }, 
                methods:{
                        addScore(){
                            //动态添加的data属性不能绑定
                            // this.user.score = 99
                            //$set可以给对象属性进行动态添加赋值，可以实现绑定
                            this.$set(this.user,'score',99)
                            console.log(this.user)
                        },
                        changeImg(){
                            // 数组成员不能直接修改，否则会导致绑定无法渲染
                            // this.imgs[this.imgIndex] = 'photo-5.jpg'
                            this.$set(this.imgs,this.imgIndex,'photo-5.jpg')
                            console.log(this.imgs)
                        }
                    }
            })
        }

    </script>
</head>

<body>
    <div id="mydiv">
        <span>{{name}}</span>
        <span>{{user.name}}</span>
        <span>{{user.score}}</span>
        <button @click='addScore'>添加学生成绩</button>
        <hr>
        <ul>
            <li v-for="(img,index) in imgs" @click='imgIndex=index'><img :src="'images/'+img" alt=""></li>
        </ul>
        <span>您选中的是第{{imgIndex+1}}张</span>
        <button @click='changeImg'>更换图片</button>
        <h1>组员添加了代码</h1>
    </div>
</body>

</html>